﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace WhatCatch.Core
{
    public class DetailPageHandler: IDetailPageHandler
    {
        CrawlerConfig _config;
        DataContainerBase _dataContainer;
        IHttpHandler _httpHandler;
        ICrawlerLog _crawlerLog;
        public DetailPageHandler(CrawlerConfig config, DataContainerBase dataContainer, IHttpHandler httpHandler, ICrawlerLog crawlerLog)
        {
            _config = config;
            _dataContainer = dataContainer;
            _httpHandler = httpHandler;
            _crawlerLog = crawlerLog;
        }

        /// <summary>
        /// 处理一次明细页面任务
        /// </summary>
        public void HandleTask(TaskContext detailTask)
        {
            try
            {
                _crawlerLog.Info($"【明细线程{detailTask.ThreadIndex}】处理明细页 {detailTask.Url}");

                //构造一个上下文
                RequestContext requestContext = new RequestContext();
                requestContext.Url = detailTask.Url;

                var html = "";
                try
                {
                    html = _httpHandler.GetHtml(requestContext.Url);
                }
                catch (Exception ex)
                {
                    _crawlerLog.Error($"【明细线程{detailTask.ThreadIndex}】异常：" + ex.ToString());
                }
                if (string.IsNullOrEmpty(html))
                {
                    _crawlerLog.Info($"【明细线程{detailTask.ThreadIndex}】url:{requestContext.Url}获取html为空");
                    Thread.Sleep(1000);
                    return;
                }
                requestContext.Html = html;

                //解析明细页内容
                Handle(requestContext);

            }
            catch (Exception ex)
            {
                _crawlerLog.Error($"【明细线程{detailTask.ThreadIndex}】处理明细页（url:{detailTask.Url}）异常：" + ex.ToString());
                //throw;
            }
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="requestContext">请求上下文</param>
        private void Handle(RequestContext requestContext)
        {
            
            requestContext.DetailHtml = "";
        }
    }
}
